//
//  KYCalendarViewController.m
//  KuaiyanCalendar
//
//  Created by 罗新 on 2017/10/17.
//  Copyright © 2017年 KuaiYan  Co.,LTD. All rights reserved.
//

#import "KYCalendarViewController.h"
#import "KYCalendarView.h"
#import "KYCalendarCell.h"
#import "NSDate+KY.h"
#import "UIView+KY.h"
#import "KYCalendarCellItem.h"
#import "KYCacheManager.h"
#define ky_signInMargin 10
#define ky_scrollViewW [UIScreen mainScreen].bounds.size.width - 2 * ky_signInMargin

@interface KYCalendarViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,KYCalendarHeaderDelegate>
/*** 日历头部 **/
@property (nonatomic, weak) KYCalendarView *calendarView;
/*** 底部scrollView **/
@property (nonatomic, weak) UIScrollView *bgScrollView;
/*** 上一页日历 **/
@property (nonatomic, weak) UICollectionView *leftCollectionView;
/*** 当前页日历 **/
@property (nonatomic, weak) UICollectionView *middleCollectionView;
/*** 下一页日历 **/
@property (nonatomic, weak) UICollectionView *rightCollectionView;
/*** 上一页数据数组 **/
@property (nonatomic, strong) NSMutableArray *lastMonthArrM;
/*** 当前页数据数组 **/
@property (nonatomic, strong) NSMutableArray *currentMonthArrM;
/*** 下一页数据数组 **/
@property (nonatomic, strong) NSMutableArray *nextMonthArrM;
/*** 当前时间戳 **/
@property (nonatomic, strong) NSDate *currentdate;
@end

@implementation KYCalendarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubviews];
    self.currentdate = [NSDate date];
    [self setUpData:self.currentdate];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)getRadomeWithMax:(NSInteger)maxValue{
    return arc4random()%maxValue;
}

- (void)setUpSubviews{
    self.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 75);
    self.view.backgroundColor = [UIColor colorWithRed:245/255. green:74/255. blue:78/255. alpha:1];
    KYCalendarView *calendarView = [[KYCalendarView alloc] initWithFrame:self.view.bounds];
    calendarView.delegate = self;
    [self.view addSubview:calendarView];
    self.calendarView = calendarView;
    
    CGFloat collectionViewW = ([UIScreen mainScreen].bounds.size.width - 2 * ky_signInMargin);
    CGFloat itemsWH = collectionViewW / 7.;
    
    //底部添加一个scrollview左右可以滑动
    UIScrollView *bgScrollView = [[UIScrollView alloc] init];
    bgScrollView.frame = CGRectMake(ky_signInMargin, 75, collectionViewW, itemsWH * 6);
    bgScrollView.contentSize = CGSizeMake(collectionViewW * 3, 0);
    bgScrollView.pagingEnabled = YES;
    bgScrollView.showsHorizontalScrollIndicator = NO;
    bgScrollView.delegate = self;
    [self.view addSubview:bgScrollView];
    self.bgScrollView = bgScrollView;
    for (int i = 0; i < 3 ; i++) {
        UICollectionViewFlowLayout *flowLayot = [[UICollectionViewFlowLayout alloc] init];
        flowLayot.sectionInset = UIEdgeInsetsZero;
        flowLayot.itemSize = CGSizeMake(itemsWH,itemsWH);
        flowLayot.minimumLineSpacing = 0;
        flowLayot.minimumInteritemSpacing = 0;
        CGRect collectionViewFrame = CGRectMake(i * collectionViewW, 0, collectionViewW, itemsWH * 6);
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:flowLayot];
        [self.bgScrollView addSubview:collectionView];
        collectionView.tag = 10 + i;
        collectionView.dataSource = self;
        collectionView.delegate = self;
        [collectionView registerClass:[KYCalendarCell class] forCellWithReuseIdentifier:@"KYCalendarCell"];
        switch (i) {
            case 0:
                self.leftCollectionView = collectionView;
                break;
            case 1:
                self.middleCollectionView = collectionView;
                break;
            case 2:
                self.rightCollectionView = collectionView;
                break;
            default:
                break;
        }
    }
    self.view.ky_height = self.rightCollectionView.ky_height + 75 + ky_signInMargin;
    self.bgScrollView.contentOffset = CGPointMake(collectionViewW, 0);
    
    //添加底部关闭按钮
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.ky_height, [UIScreen mainScreen].bounds.size.width, 70)];
    footerView.backgroundColor = [UIColor clearColor];
    UIButton *closeBtn = [[UIButton alloc] init];
    closeBtn.frame = CGRectMake(0, 0, 70, 70);
    [closeBtn setBackgroundImage:[UIImage ky_imageNamed:@""] forState:UIControlStateNormal];
    
    
}

- (void)setUpData:(NSDate *)date{
    //移除数组
    [self.lastMonthArrM removeAllObjects];
    [self.currentMonthArrM removeAllObjects];
    [self.nextMonthArrM removeAllObjects];
    
    KYCacheManager *cacheMgr = [KYCacheManager shareInstance];
    
    NSDate *lastDate = [NSDate lastMonth:date];
    NSDate *nextDate = [NSDate nextMonth:date];
    
    NSInteger lastlastYear = [NSDate year:[NSDate lastMonth:lastDate]];
    NSInteger lastlastMonth = [NSDate month:[NSDate lastMonth:lastDate]];
    
    NSInteger lastYear = [NSDate year:lastDate];
    NSInteger lastMonth = [NSDate month:lastDate];
    
    NSInteger currentYear = [NSDate year:date];
    NSInteger currentMonth = [NSDate month:date];
    
    NSInteger nextYear = [NSDate year:nextDate];
    NSInteger nextMonth = [NSDate month:nextDate];
    
    NSInteger nextnextYear = [NSDate year:[NSDate nextMonth:nextDate]];
    NSInteger nextnextMonth = [NSDate month:[NSDate nextMonth:nextDate]];
    
    
    //0.上月1号所在星期
    NSInteger firstWeekdayLastM = [NSDate firstWeekdayInThisMonth:lastDate];
    //1.上月总共天数
    NSInteger totalDaysOfLastM = [NSDate totaldaysInMonth:lastDate];
    //2.上上月总共天数
    NSInteger totalDaysOfLastLastM = [NSDate totaldaysInMonth:[NSDate lastMonth:lastDate]];
    //3.将日期放入数组
    for (NSInteger i = totalDaysOfLastLastM - firstWeekdayLastM + 1; i <= totalDaysOfLastLastM; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",lastlastYear,lastlastMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = NO;
            [self.lastMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:NO year:lastlastYear month:lastlastMonth day:i continuityTime:0];
            [self.lastMonthArrM addObject:item];
        }
    }
    for (NSInteger i = 1; i <= totalDaysOfLastM; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",lastYear,lastMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = YES;
            [self.lastMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:YES year:lastYear month:lastMonth day:i continuityTime:0];
            [self.lastMonthArrM addObject:item];
        }
    }
    for (NSInteger i = 1; i <= 42 - firstWeekdayLastM - totalDaysOfLastM; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",currentYear,currentMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = NO;
            [self.lastMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:NO year:currentYear month:currentMonth day:i continuityTime:0];
            [self.lastMonthArrM addObject:item];
        }
    }
    
    //0.本月1号所在星期
    NSInteger firstWeekday = [NSDate firstWeekdayInThisMonth:date];
    //1.本月总共天数
    NSInteger totalDaysOfMonth = [NSDate totaldaysInMonth:date];
    //2.上月总共天数
    NSInteger totalDaysOfLastMonth = [NSDate totaldaysInMonth:[NSDate lastMonth:date]];
    //3.将日期放入数组
    for (NSInteger i = totalDaysOfLastMonth - firstWeekday; i < totalDaysOfLastMonth; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",lastYear,lastMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = NO;
            [self.currentMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:NO year:lastYear month:lastMonth day:i continuityTime:0];
            [self.currentMonthArrM addObject:item];
        }
    }
    for (NSInteger i = 1; i <= totalDaysOfMonth; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",currentYear,currentMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = YES;
            [self.currentMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:YES year:currentYear  month:currentMonth day:i continuityTime:0];
            [self.currentMonthArrM addObject:item];
        }
    }
    for (NSInteger i = 1; i <= 42 - firstWeekday - totalDaysOfMonth; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",nextYear,nextMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = NO;
            [self.currentMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:NO year:nextYear  month:nextMonth day:i continuityTime:0];
            [self.currentMonthArrM addObject:item];
        }
    }
    
    
    //0.下月1号所在星期
    NSInteger firstWeekdayNextM = [NSDate firstWeekdayInThisMonth:nextDate];
    //1.下月总共天数
    NSInteger totalDaysOfNextM = [NSDate totaldaysInMonth:nextDate];
    //2.本月总共天数
    NSInteger totalDaysOfCurrentM = [NSDate totaldaysInMonth:date];
    //3.将日期放入数组
    for (NSInteger i = totalDaysOfCurrentM - firstWeekdayNextM + 1; i <= totalDaysOfCurrentM; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",currentYear,currentMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = NO;
            [self.nextMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:NO year:currentYear  month:currentMonth day:i continuityTime:0];
            [self.nextMonthArrM addObject:item];
        }
    }
    for (NSInteger i = 1; i <= totalDaysOfNextM; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",nextYear,nextMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = YES;
            [self.nextMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:YES year:nextYear  month:nextMonth day:i continuityTime:0];
            [self.nextMonthArrM addObject:item];
        }
    }
    for (NSInteger i = 1; i <= 42 - firstWeekdayNextM - totalDaysOfNextM; i ++) {
        NSString *cacheKey = [NSString stringWithFormat:@"KYCalendar%ld%ld%ld",nextnextYear,nextnextMonth,i];
        BOOL isContains= [cacheMgr ky_isContainObjectForKey:cacheKey];
        if (isContains) {
            KYCalendarCellItem *item = (KYCalendarCellItem *)[cacheMgr ky_ObjectForKey:cacheKey];
            item.highLight = NO;
            [self.nextMonthArrM addObject:item];
        }else{
            KYCalendarCellItem *item = [KYCalendarCellItem calendarCellItemWithIconType:0 isHighLight:NO year:nextnextYear  month:nextnextMonth day:i continuityTime:0];
            [self.nextMonthArrM addObject:item];
        }
    }
    NSInteger year = [NSDate year:self.currentdate];
    NSInteger month = [NSDate month:self.currentdate];
    self.calendarView.calendarLabel.text = [NSString stringWithFormat:@"%ld年%ld月",year,month];
    [self.rightCollectionView reloadData];
    [self.middleCollectionView reloadData];
    [self.leftCollectionView reloadData];
}

#pragma mark - collectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 42;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KYCalendarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"KYCalendarCell" forIndexPath:indexPath];
    KYCalendarCellItem *item;
    switch ([collectionView tag] - 10){
        case 0:
            item = self.lastMonthArrM[indexPath.row];
            break;
        case 1:
            item = self.currentMonthArrM[indexPath.row];
            break;
        case 2:
            item = self.nextMonthArrM[indexPath.row];
            break;
        default:
            break;
    }
    cell =  [cell refreshDataWithItem:item];
    return cell;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;{
    CGPoint offset = scrollView.contentOffset;
    NSInteger page = offset.x / ([UIScreen mainScreen].bounds.size.width - 2 * ky_signInMargin);
    switch (page) {
        case 0:
            self.currentdate = [NSDate lastMonth:self.currentdate];
            [self setUpData:self.currentdate];
            [scrollView setContentOffset:CGPointMake(ky_scrollViewW, 0) animated:NO];
            break;
        case 1:
            break;
        case 2:
            self.currentdate = [NSDate nextMonth:self.currentdate];
            [self setUpData:self.currentdate];
            [scrollView setContentOffset:CGPointMake(ky_scrollViewW, 0) animated:NO];
            break;
        default:
            break;
    }
}

#pragma mark - calendarHeaderDdelegate
- (void)calendarHeaderNavButtonClick:(NSInteger)count{
    self.currentdate = [NSDate designatedMonth:self.currentdate count:count];
    [self setUpData:self.currentdate];
}

#pragma mark - Lazy load
- (NSMutableArray *)currentMonthArrM{
    if (!_currentMonthArrM) {
        _currentMonthArrM = [NSMutableArray array];
    }
    return _currentMonthArrM;
}
- (NSMutableArray *)lastMonthArrM{
    if (!_lastMonthArrM) {
        _lastMonthArrM = [NSMutableArray array];
    }
    return _lastMonthArrM;
}
- (NSMutableArray *)nextMonthArrM{
    if (!_nextMonthArrM) {
        _nextMonthArrM = [NSMutableArray array];
    }
    return _nextMonthArrM;
}
@end
